package com.weiaibenpao.demo.chislim.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.orhanobut.logger.Logger;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.base.BaseActivity;
import com.weiaibenpao.demo.chislim.db.preferences.RunningPreferences;
import com.weiaibenpao.demo.chislim.db.preferences.UserPreferences;
import com.weiaibenpao.demo.chislim.jpush.TagAliasOperatorHelper;
import com.weiaibenpao.demo.chislim.service.RunningService;
import com.weiaibenpao.demo.chislim.ui.activity.ble.BleActivity;
import com.weiaibenpao.demo.chislim.ui.activity.login.LoginActivity;
import com.weiaibenpao.demo.chislim.ui.fragment.DiscoverFragment;
import com.weiaibenpao.demo.chislim.ui.fragment.MeFragment;
import com.weiaibenpao.demo.chislim.ui.fragment.MomentFragment;
import com.weiaibenpao.demo.chislim.ui.fragment.RunningFragment;
import com.weiaibenpao.demo.chislim.utils.LocationUtil;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.OnClick;

import static com.weiaibenpao.demo.chislim.jpush.TagAliasOperatorHelper.sequence;


public class MainActivity extends BaseActivity {
    private static final String IS_EXIT = "is_exit";
    private static final String CURRENT_TAG = "current_tag";
    private static final String TAG_RUNNING = "0";
    private static final String TAG_DISCOVER = "1";
    private static final String TAG_MOMENT = "2";
    private static final String TAG_ME = "3";
    private String mCurrentTag;
    private Handler handler;
    private LocationUtil mLocationUtil;

    @BindViews({R.id.iv_tab_running,R.id.iv_tab_discover,R.id.iv_tab_moment,R.id.iv_tab_me})
    ImageView[] mTabIcons;
    @BindViews({R.id.tv_tab_running,R.id.tv_tab_discover,R.id.tv_tab_moment,R.id.tv_tab_me})
    TextView[] mTabTexts;
    @BindView(R.id.gotoBle)
    Button gotoBle;

    @Override
    public int setLayoutResourceID() {
        return R.layout.activity_main;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        // ToDo 项目分包（目录结构）计步模块解耦并集成为独立模块  高德集成  百度语音  LeakCanary集成  MainActivity四个Tab  极光推送(通知，自定义消息，别名)--完成
        // ToDo ObjectBox数据库集成  封装通用标题栏  封装高德定位  使用第三方字体  RunningService  BaseRunningActivity封装--完成
        // ToDo 腾讯Bugly  友盟统计等统计平台
        // 奇怪的线程池持有TestActivity实例内存泄露(极光所致)  内存泄露
        // 帮解决中国跑断室内室外和Region重绘断笔--搞定      微博微信登录失败--nailed it  三星无法保存数据--nailed it  跑步记录item时间显示错乱秒数超3883
        // RunningDataView增加文字
        // release apk登录失败 推测是混淆所致--已确认是混淆所致--搞定      SocketTimeoutException--友盟问题
        // 帮修改跑步历史。。(字体，保留小数位，显示小时值，分页，点击事件)
        // 补上漏掉的跑圈详情删除和举报功能
        // logo
        // 常规跑上传数据 --ok
        // 启动页--ok
        // 从Splash跳转登录还是main的逻辑--ok
        // 发布界面发布成功，那么setResult通知列表更新--ok
        String tag = TAG_RUNNING;
        if (savedInstanceState != null) {
            tag = savedInstanceState.getString(CURRENT_TAG, TAG_RUNNING);//获取activity被销毁前显示的tab对应的tag
        }
        switchFragment(tag);
        updateTabBtn(Integer.parseInt(tag));
//        handler = new Handler();
//        testRedDot();
//        testSetAlias(ACTION_SET);
        initLocation();
        recoverRunning();
        Logger.e("MainAct--onCreate");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Logger.e("MainAct--onStop");
    }

    public static void startSelf(Context context){
        Intent intent = new Intent(context,MainActivity.class);
        context.startActivity(intent);
    }

    public static void startSelfToExit(Context context){
        Intent intent = new Intent(context,MainActivity.class);
        intent.putExtra(IS_EXIT,true);
        context.startActivity(intent);
    }

    private void recoverRunning() {
        int state = RunningPreferences.getInstance().getRunningState();
        if(RunningService.RUNNING == state || RunningService.PAUSE == state){
            //该写法并不兼容Nexus 5x 从Recent列表杀掉应用但杀不死服务的情况，可以换成直接打开上次的跑步Activity
//            Intent serviceIntent = new Intent(this, RunningService.class);
//            serviceIntent.putExtra(RunningService.RUNNING_ACTIVITY,RunningPreferences.getInstance().getRunningActivity());
//            startService(serviceIntent);

            String runningActivity = RunningPreferences.getInstance().getRunningActivity();
            Intent intent = new Intent(runningActivity);
            startActivity(intent);
        }
    }

    private void initLocation() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { //用户授予了定位权限
            mLocationUtil = new LocationUtil(this);
            mLocationUtil.startLocation();
        }
    }

    private void testSetAlias(int action) {
        final TagAliasOperatorHelper.TagAliasBean tagAliasBean = new TagAliasOperatorHelper.TagAliasBean();
        tagAliasBean.action = action;
        sequence = 101;
        tagAliasBean.alias = "zjl1";
        tagAliasBean.isAliasAction = true;
        TagAliasOperatorHelper.getInstance().handleAction(getApplicationContext(),sequence,tagAliasBean);
//        handler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                tagAliasBean.alias = "zjl2100";
////                sequence = 202;
//                TagAliasOperatorHelper.getInstance().handleAction(getApplicationContext(),sequence,tagAliasBean);
//                Logger.e("二次设置别名");
//            }
//        },20000);
//        handler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                tagAliasBean.alias = "zjl";
////                sequence =303;
//                TagAliasOperatorHelper.getInstance().handleAction(getApplicationContext(),sequence,tagAliasBean);
//                Logger.e("三次设置别名");
//            }
//        }, 30000);
    }

    private void testRedDot() {
        //模拟推送来的消息
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                UserPreferences.getInstance().setUnreadMsgCount(2);
                updateTabBtn(Integer.parseInt(mCurrentTag));
            }
        },3000);
        //模拟消息已读
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                UserPreferences.getInstance().setUnreadMsgCount(0);
                updateTabBtn(Integer.parseInt(mCurrentTag));
            }
        },6000);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(CURRENT_TAG, mCurrentTag);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if(intent != null){
            boolean isExit = intent.getBooleanExtra(IS_EXIT,false);
            if(isExit){
                Logger.e("MainAct onNewIntent--exit app");
                this.finish();
                //以下代码本来可以直接在MainActivity.startSelfToExit()后直接调用，不过貌似系统机制变化，现在需要这样写
                LoginActivity.startSelf(this);
            }
        }
    }


    private void switchFragment(String newTag) {
        if (isFragmentShown(newTag)) {
            return;
        }
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        Fragment newFragment = getSupportFragmentManager().findFragmentByTag(newTag);
        if (newFragment == null) {
            newFragment = getFragmentInstance(newTag);
            transaction.add(R.id.main_container, newFragment, newTag);
        } else {
            transaction.show(newFragment);
        }
        Fragment currentFragment = getSupportFragmentManager().findFragmentByTag(mCurrentTag);
        if (currentFragment != null && !currentFragment.isHidden()) {
            transaction.hide(currentFragment);
        }
        transaction.commit();
        mCurrentTag = newTag;
    }


    private boolean isFragmentShown(String newTag) {
        if (newTag.equals(mCurrentTag)) {
            return true;
        }
        return false;
    }


    public Fragment getFragmentInstance(String tag) {
        Fragment fragment;
        if (TextUtils.equals(tag, TAG_RUNNING)) {
            fragment = new RunningFragment();
        } else if (TextUtils.equals(tag, TAG_DISCOVER)) {
            fragment = new DiscoverFragment();
        } else if (TextUtils.equals(tag, TAG_MOMENT)) {
            fragment = new MomentFragment();
        } else if (TextUtils.equals(tag, TAG_ME)) {
            fragment = new MeFragment();
        } else {
            fragment = new RunningFragment();
        }
        return fragment;
    }


    @OnClick({R.id.ll_tab_running, R.id.ll_tab_discover, R.id.ll_tab_moment, R.id.ll_tab_me , R.id.gotoBle})
    public void onClickTab(View view) {
        switch (view.getId()) {
            case R.id.ll_tab_running:
                switchFragment(TAG_RUNNING);
                updateTabBtn(0);
                break;
            case R.id.ll_tab_discover:
                switchFragment(TAG_DISCOVER);
                updateTabBtn(1);
                break;
            case R.id.ll_tab_moment:
                switchFragment(TAG_MOMENT);
                updateTabBtn(2);
                break;
            case R.id.ll_tab_me:
                switchFragment(TAG_ME);
                updateTabBtn(3);
                break;
            case R.id.gotoBle:
                startActivity(new Intent(this , BleActivity.class));
                break;
        }
    }

    public void updateTabBtn(int  index){
        if(mTabIcons == null){
            return;
        }
        for (int i = 0; i < mTabIcons.length; i++) {
            if(i == index){
                mTabTexts[i].setTextColor(getResources().getColor(R.color.colorTabTextSelected));
                if(i == 2 && UserPreferences.getInstance().getUnreadMsgCount()>0){
                    mTabIcons[i].setImageLevel(40);
                }else {
                    mTabIcons[i].setImageLevel(20);
                }
            }else {
                mTabTexts[i].setTextColor(getResources().getColor(R.color.colorTabTextDefault));
                if(i == 2 && UserPreferences.getInstance().getUnreadMsgCount()>0){
                    mTabIcons[i].setImageLevel(30);
                }else {
                    mTabIcons[i].setImageLevel(10);
                }
            }
        }
    }


    @Override
    protected void onDestroy() {
        if(mLocationUtil != null) mLocationUtil.destroyLocation();
        super.onDestroy();
//        testSetAlias(ACTION_DELETE);
        Logger.e("MainAct--onDestroy");
    }


}
